package com.lifp.config.oauth.detail;

import com.lifp.entity.SysPermission;
import com.lifp.entity.SysUser;
import com.lifp.service.SysPermissionService;
import com.lifp.service.SysUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2022/8/12
 * @Version 1.0
 */
@Service
public class UserDetailsServiceImpl implements CustomUserDetailService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库查询用户信息
        SysUser sysUser = sysUserService.getByUserName(username);

        //用户非空，进行授权
        if (sysUser != null) {
            List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();

            //根据用户id，查询权限列表
            List<SysPermission> sysPermissions = permissionService.selectListByUserId(sysUser.getUserId());
            sysPermissions.forEach(sysPermission -> {
                SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
                grantedAuthorities.add(grantedAuthority);
            });

            return new User(sysUser.getUsername(),sysUser.getPassword(), grantedAuthorities);
        }

        return null;
    }

    @Override
    public UserDetails loadUserByWXOpenId(String openId) throws UsernameNotFoundException {
        return null;
    }
}
